package com.vecharm.app.utils

import com.ling.sdk.http.ApiCallBack
import com.ling.sdk.http.ApiObserver
import com.ling.sdk.http.ApiResponseBean
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers

inline fun <reified T> getService(): T {
    return RequestManager.getRetrofit().create(T::class.java)
}

fun <T : ApiResponseBean> Observable<T>.request(callBackC: CallBack<T>.() -> Unit) {
    val callBack = CallBack<T>()
    callBackC.invoke(callBack)
    val apiCallBack = object : ApiCallBack<T>() {
        override fun onSuccess(data: T) {
            callBack.onSuccess?.invoke(data)
        }

        override fun onError(errorCode: String, message: String?) {
            callBack.onErrorMessage?.invoke(errorCode, message)
        }


        override fun onCompleted() {
            callBack.onCompleted?.invoke()
        }


    }
    this.observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(ApiObserver(apiCallBack))
}


class CallBack<T> {

    var onCompleted: (() -> Unit)? = null

    var onSuccess: ((data: T) -> Unit)? = null

    var onErrorMessage: ((errorCode: String, message: String?) -> Unit)? = null

}

